<?php
// +----------------------------------------------------------------------
// | Description: 合同
// +----------------------------------------------------------------------
// | Author: Michael_xu | gengxiaoxu@5kcrm.com 
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use app\admin\model\Record;
use think\Hook;
use think\Request;
use think\Db;

class Accounting extends ApiCommon
{
    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
    **/    
    public function _initialize()
    {
        $action = [
            'permission'=>[''],
            'allow'=>['userlist']
        ];
        Hook::listen('check_auth',$action);
        $request = Request::instance();
        $a = strtolower($request->action());        
        if (!in_array($a, $action['permission'])) {
            parent::_initialize();
        }
    }
    //2023-12-19 lina 新增 start
    /**
     * 记账板块列表
     * */
    public function index()
    {
        $contractModel = model('Contract');
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $param['check_status'] =2;
        //$param['is_ok'] =0;
        $param['is_accounting'] =1;
        $data = $contractModel->getAccountingList($param,1);
        return resultArray(['data' => $data]);
    }

    /**
     * 捡取
     * */
    public function picking()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $contractModel = model('Contract');
        $contract_ids = $param['contract_id'];
        if (!$contract_ids || !is_array($contract_ids)) {
            return resultArray(['error' => '请选择需要捡取的工单']);
        }
        $errorMessage = [];
        foreach ($contract_ids as $k=>$v) {
            $dataName = $contractModel->where(['contract_id' => $v])->value('name');
            $accounting_id = $contractModel->where(['contract_id' => $v])->value('accounting_id');
            if($accounting_id){
                $errorMessage[] = '请不要已捡取成功！请不要重复捡取！';
                continue;
            }
            $data = ["accounting_status"=>1,"accounting_id"=>$userInfo["id"],"accounting_time"=>time()];
            $resCustomer = $contractModel->where(['contract_id' => $v,"accounting_status"=>0])->update($data);
            if (!$resCustomer) {
                $errorMessage[] = '工单《'.$dataName.'》捡取失败，错误原因：数据出错；';
                continue;
            }
            //修改记录
            //updateActionLog($userInfo['id'], 'crm_contract', $v, '', '', '捡取了工单');
        }
        if (!$errorMessage) {
            return resultArray(['data' => '捡取成功']);
        } else {
            return resultArray(['error' => $errorMessage]);
        }
    }
    /**
     * 分配
     * */
    public function allocation()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        if(!isset($param["accountancy_user_id"])) return resultArray(['error' => '请选择做账会计']);
        if(!isset($param["consult_user_id"])) return resultArray(['error' => '请选择咨询会计']);


        $contract=$this->check($param);
        if(isset($contract["code"])){
            return resultArray(['error' => $contract["error"]]);
        }
        if($contract["accounting_id"]!=$userInfo["id"]){
            return resultArray(['error' => '您不可分配该记账工单']);
        }
        $param["accounting_status"]=2;
        $customerModel = model('Customer');
        //启动事务
        Db::startTrans();
        try {
            $contract->save($param);
            $customerModel->where(["customer_id"=>$contract["customer_id"]])
                ->update(["consult_user_id"=>$param["consult_user_id"]]);
            Db::commit();
            $res=true;
        } catch(\Exception $e) {
            // 回滚事务
            Db::rollback();
            return resultArray(['error' => '失败']);
        }
        if($res){
            return resultArray(['data' => '成功']);
        }
    }
    /**
     * 咨询会计填写开始时间
     * */
    public function startService()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        if(!isset($param["accounting_start_time"])) return resultArray(['error' => '请选择记账开始时间']);

        $contract=$this->check($param);
        if(isset($contract["code"])){
            return resultArray(['error' => $contract["error"]]);
        }
        if($contract["consult_user_id"]!=$userInfo["id"]){
            return resultArray(['error' => '您不是该订单的咨询会计！不能开始服务！']);
        }
        $param["accounting_start_time"]=strtotime($param["accounting_start_time"]);
        $param["accounting_end_time"]=strtotime("+".$contract["crm_grvgkz"]."month",$param["accounting_start_time"]);
        $customerModel = model('Customer');
        //启动事务
        Db::startTrans();
        try {
            $contract->save($param);
            $customerModel->where(["customer_id"=>$contract["customer_id"]])
                ->update(["consult_user_id"=>$param["consult_user_id"]]);
            Db::commit();
            $res=true;
        } catch(\Exception $e) {
            // 回滚事务
            Db::rollback();
            return resultArray(['error' => '失败']);
        }
        if($res){
            return resultArray(['data' => '成功']);
        }
    }
    /**
     * 获取做账会计
     * */
    public function userlist()
    {
        $contractModel = model('Contract');
        $type= !isset($this->param["type"])?1:$this->param["type"];
        $data = $contractModel->accountancyUserList($type);
        return resultArray(['data' => $data]);
    }
    /**
     * 检测工单状态
     * */
    private function check($param){
        $contractModel = model('Contract');
        if (!isset($param['contract_id'])) {
            return ["code"=>400,'error' => '请选择记账工单'];
        }
        $contract=$contractModel->where(["contract_id"=>$param['contract_id']])->find();
        if(empty($contract)){
            return ["code"=>400,'error' => '记账工单不存在'];
        }
        if($contract["is_accounting"]!=1){
            return ["code"=>400,'error' => '工单未流转到记账板块'];
        }
        if(empty($contract["accounting_id"])){
            return ["code"=>400,'error' => '工单未捡取'];
        }
        return $contract;
    }
    /**
     * 填写工本费
     * */
    public function cost()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        if(!isset($param["cost_production"])) return resultArray(['error' => '请输入工本费']);
        if(!in_array($param['cost_production'],[0,200])) return resultArray(['error' => '工本费只允许输入0,200']);
        $contract=$this->check($param);
        if(isset($contract["code"])){
            return resultArray(['error' => $contract["error"]]);
        }
        if($contract["accounting_id"]!=$userInfo["id"]){
            return resultArray(['error' => '您不能填写该工单工本费']);
        }
        /*$receivablesModel = new \app\crm\model\Receivables();
        $receivablesMoney = $receivablesModel->getMoneyByContractId($contract["contract_id"]);
        $contract["crm_oeseng"] = $receivablesMoney["hsOeseng"];
        if($param["cost_production"]>$contract["crm_oeseng"]){
            return resultArray(['error' => '工本费不能超过核定成本']);
        }*/
        $accountingModel = model('Accounting');

        if($contract["cost_production"]!=$param["cost_production"]){
            //改变了工本费
            $contract["cost_production"]=$param["cost_production"];
            $price=$accountingModel->monthlyAgencyPrice($contract);
            $param["monthly_agency_price"]=$price;
        }
        $contract->allowField(true)->save($param);
        return resultArray(['data' => '成功']);
    }

    /**
     * 做账
     * */
    public function make()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        if(!isset($param["year"])) return resultArray(['error' => '请选择年份']);
        if(!isset($param["month"])) return resultArray(['error' => '请选择月份']);
        $yearMonth=date("Y-m",strtotime("{$param["year"]}-{$param["month"]}"));//做账的年月
        //判断只能做当月以及之前的账
        if($yearMonth > date("Y-m")){
            return resultArray(['error' => '做账时间未到！请等待！']);
        }
        $contract=$this->check($param);
        if(isset($contract["code"])){
            return resultArray(['error' => $contract["error"]]);
        }
        if($contract["accounting_end_time"]<time()) return resultArray(['error' => '该记账工单已结束']);
        if($contract["accountancy_user_id"]!=$userInfo["id"]){
            return resultArray(['error' => '对不起！您不是本订单的做账人员！']);
        }
        $start_year=date("Y",$contract["accounting_start_time"]);
        $end_year=date("Y",$contract["accounting_end_time"]);

        if (!($param["year"]<=$end_year && $param["year"]>=$start_year)){
            //判断年份不在做账期内
            return resultArray(['error' => '该年份不在做账期内']);
        }
        $accountingModel = model('Accounting');
        $accounting=$accountingModel->whereIn("status",[0,1])->where(["accountancy_user_id"=>$userInfo["id"],"year"=>$param["year"],"month"=>$param["month"],"contract_id"=>$contract["contract_id"]])->find();
        if(!empty($accounting)) return resultArray(['error' => '该月份已做账']);
        $accounting=$accountingModel->whereIn("status",[0,1])
            ->where(["accountancy_user_id"=>$userInfo["id"],"contract_id"=>$contract["contract_id"]])->count();
        if($accounting>=$contract["available"]) return resultArray(['error' => '可做账次数不足']);
        //启动事务
        Db::startTrans();
        try {
            $data=[
                "accountancy_user_id"=>$userInfo["id"],
                "contract_id"=>$contract["contract_id"],
                "year"=>$param["year"],
                "month"=>$param["month"],
                "memo"=>$param["memo"],
                "admin_id"=>$contract["accounting_id"],//分配的人来审核
            ];
            $accountingModel->save($data);
            if($contract["state"]==3) $contract->save(["state"=>4]);
            Db::commit();
            $res=true;
        } catch(\Exception $e) {
            // 回滚事务
            Db::rollback();
            return resultArray(['error' => '失败']);
        }
        if($res){
            return resultArray(['data' => '成功']);
        }
    }

    /**
     * 做账列表
     * */
    public function makelist()
    {
        $accountingModel = model('Accounting');
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $data = $accountingModel->getDataList($param,1);
        return resultArray(['data' => $data]);
    }

    /**
     * 审核做账
     * */
    public function examine()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        if(!isset($param["status"])) return resultArray(['error' => '请选择审核状态']);
        $contract=$this->check($param);
        if(isset($contract["code"])){
            return resultArray(['error' => $contract["error"]]);
        }
        if($contract["accounting_end_time"]<time()) return resultArray(['error' => '该记账工单已结束']);
        /*if($contract["accountancy_user_id"]!=$userInfo["id"]){
            return resultArray(['error' => '您不可做账']);
        }*/
        if($contract["accounting_id"]!=$userInfo["id"]){
            return resultArray(['error' => '您不可审核此做账']);
        }
        $accountingModel = model('Accounting');
        $accounting=$accountingModel->where(["accounting_id"=>$param["accounting_id"]])->find();
        if(empty($accounting)) return resultArray(['error' => '做账记录不存在']);
        $accounting->save([
            "remark"=>$param["remark"],
            "status"=>$param["status"],
            "examine_time"=>time(),
        ]);
        return resultArray(['data' => '成功']);
    }

}
